package cn.edu.anan.websocket;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 扫码登录controller
 *
 * @author ThinkPad
 * @version 1.0
 * @date 2021/6/23 20:43
 */
@Controller
@RequestMapping("/qr")
public class QrCodeController {

    /**
     * 存储uuid
     */
    private static final Map<String,Integer> UUID_MAP = new ConcurrentHashMap<String,Integer>();

    /**
     * 跳转登录主页面
     * @return
     */
    @GetMapping("/toLogin")
    public ModelAndView toLogin() {
        ModelAndView mav = new ModelAndView("/login");
        return mav;
    }

    /**
     *绑定用户
     * @return
     */
    @RequestMapping(value = "/bind" ,method = RequestMethod.GET)
    @ResponseBody
    public Object bindUserIdAndToken(@RequestParam("token") String token) throws Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","ok");
        jsonObject.put("userId","888");
        jsonObject.put("projId","def");
        QrWebSocketServer.sendInfo(jsonObject.toJSONString(1),token);
        return "ok";

    }

    /**
     * 获取登录二维码、放入Token
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getLoginQr" ,method = RequestMethod.GET)
    public void createCodeImg(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        try {
            // 生成uuid
            String uuid = UUID.randomUUID().toString();
            UUID_MAP.putIfAbsent(uuid,1);
            response.setHeader("uuid", uuid);

            // 生成二维码
            String path = "http://localhost:8888/qr/bind/?token="+uuid;
            QrCodeUtil.generate(path, 300, 300, "jpg",response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
